package com.esd.csair;

import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import org.apache.log4j.Logger;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Cache;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class CsairWebClient extends WebClient implements Serializable{

	private static Logger log = Logger.getLogger(CsairWebClient.class);
	
	public CsairWebClient(final BrowserVersion browserVersion) {
		super(browserVersion);
	}

	private static final long serialVersionUID = -4606970256910595579L;

	/**
	 * 
	 *
	 * @author snailzhang
	 * @date 2017年8月18日
	 *
	 * @param url
	 *            加载的地址
	 * @param windowName
	 *            打开窗口的名称，重要，用来提取缓存。
	 * @param cache
	 *            是否重新开启，true 重新开启，false 使用缓存。
	 * @return
	 * @throws IOException
	 * @throws FailingHttpStatusCodeException
	 * @throws MalformedURLException
	 */
	public CsairPage getCsairHtmlPage(String url, String windowName, Boolean cache) {
		URL l = null;
		try {
			l = new URL(url);
		} catch (MalformedURLException e1) {
			log.error("MalformedURLException", e1);
		}
		int whileCount=1;
		CsairPage csairHtmlPage = new CsairPage();
		if (cache) {
			WebWindow webWindos = null;
			try {
				webWindos = getWebWindowByName(windowName);
				Page page = webWindos.getEnclosedPage();
				if (page.isHtmlPage()) {
					HtmlPage htmlPage = (HtmlPage) page;
					csairHtmlPage.setHtmlPage(htmlPage);
					csairHtmlPage.setLS(CS.NONE);
					return csairHtmlPage;
				}
			} catch (Exception e) {
				log.error("Exception", e);
				WebWindow w0 = getWebWindows().get(0);
				webWindos = openWindow(l, windowName, w0);
				Page page = webWindos.getEnclosedPage();
				while(page == null){
					whileCount++;
				      log.error("第"+whileCount+"次，page==>null");
				      try {
						Thread.sleep(200);
					} catch (InterruptedException e1) {
						log.error("InterruptedException", e1);
						Thread.currentThread().interrupt();
					}
						webWindos = openWindow(l, windowName, w0);
						page = webWindos.getEnclosedPage();
						if (page.isHtmlPage()) {
							HtmlPage htmlPage = (HtmlPage) page;
							csairHtmlPage.setHtmlPage(htmlPage);
							csairHtmlPage.setLS(CS.NONE);
							return csairHtmlPage;
						}
						if(whileCount==10) {
						       break;
						     }
				}
				if (page.isHtmlPage()) {
					HtmlPage htmlPage = (HtmlPage) page;
					csairHtmlPage.setHtmlPage(htmlPage);
					csairHtmlPage.setLS(CS.NONE);
					return csairHtmlPage;
				}
			}
		} else {
			WebWindow webWindos = null;
			WebWindow w0 = getWebWindows().get(0);
			webWindos = openWindow(l, windowName, w0);
			Page page = webWindos.getEnclosedPage();
			while(page == null){
				whileCount++;
			      log.error("第"+whileCount+"次，page==>null");
			      try {
					Thread.sleep(200);
				} catch (InterruptedException e1) {
					log.error("InterruptedException", e1);
					 Thread.currentThread().interrupt();
				}
					webWindos = openWindow(l, windowName, w0);
					page = webWindos.getEnclosedPage();
					if (page.isHtmlPage()) {
						HtmlPage htmlPage = (HtmlPage) page;
						csairHtmlPage.setHtmlPage(htmlPage);
						csairHtmlPage.setLS(CS.NONE);
						return csairHtmlPage;
					}
					if(whileCount==10) {
					       break;
					     }
			}
			if (page.isHtmlPage()) {
				HtmlPage htmlPage = (HtmlPage) page;
				log.info("cache为false==htmlpage==>"+htmlPage);
				csairHtmlPage.setHtmlPage(htmlPage);
				csairHtmlPage.setLS(CS.NONE);
				return csairHtmlPage;
			}
		}
		return csairHtmlPage;

	}

	public CsairPage getCsairJsonObjectPage(String url)
			throws IOException, FailingHttpStatusCodeException, MalformedURLException {
		CsairPage csairHtmlPage = new CsairPage();
		WebWindow webWindos = null;
		WebWindow w0 = getWebWindows().get(0);
		webWindos = openWindow(new URL(url), "checkLogin", w0);
		Page page = webWindos.getEnclosedPage();
		WebResponse response = page.getWebResponse();
		log.info(response.getContentType());// application/xhtml+xml
		if (response.getContentType().equals("application/json")) {
			String json = response.getContentAsString();
			JSONObject jsonObject = JSONObject.fromObject(json);
			csairHtmlPage.setJsonObject(jsonObject);
			csairHtmlPage.setLS(CS.NONE);
		}
		return csairHtmlPage;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> getCsairXMLPage(String url)
			throws IOException, FailingHttpStatusCodeException, MalformedURLException {
		CsairPage csairHtmlPage = new CsairPage();
		WebWindow webWindos = null;
		WebWindow w0 = getWebWindows().get(0);
//		if(url.startsWith("http://b2c.csair.com/portal/ordermanage/planeOrder/queryPlaneOrders")){
//			webWindos = openWindow(new URL(url), "OrderXml", w0);
//			url = "http://b2c.csair.com/portal/ordermanage/planeOrder/queryPlaneOrders?groupflag=0&bookTimeFrom=2017-02-24";
//		}
		webWindos = openWindow(new URL(url), "OrderXml", w0);
//		webWindos.getHistory().go(0);
//		try {
//			webWindos.wait(1000);
//		} catch (InterruptedException e1) {
//			e1.printStackTrace();
//		}
//		log.info("---------------------页面刷新！！--------------------");
		Page page = webWindos.getEnclosedPage();
		
		WebResponse response = page.getWebResponse();
		   int whileCount=1;
		   int startusCode=response.getStatusCode();
			while(startusCode==404) {
		      whileCount++;
		      log.error("第"+whileCount+"次，查询订单404重新查询中。。。。");
		      try {
		        Thread.sleep(200);
		      } catch (InterruptedException e) {
		    	  log.error("InterruptedException", e);
		    	  Thread.currentThread().interrupt();
		      }
		      webWindos = openWindow(new URL(url), "OrderXml", w0);
		      page = webWindos.getEnclosedPage();
		      response = page.getWebResponse();
		      startusCode=response.getStatusCode();
		      if(whileCount==10) {
		        break;
		      }
		    }
		log.info(response.getContentType());// application/xhtml+xml
		if (response.getContentType().equals("application/xhtml+xml")) {
			Map<String, Object> xml = XmlExercise.xml2json(response.getContentAsString());
			csairHtmlPage.setLS(CS.NONE);
//			page.cleanUp();
			webWindos = null;
			Cache c = getCache();
			c.setMaxSize(0);
			setCache(c);
			return xml;
		}
		return null;
	}

	public CsairPage getCsairJsonArrayPage(String url)
			throws IOException, FailingHttpStatusCodeException, MalformedURLException {
		CsairPage csairHtmlPage = new CsairPage();
		Page page = super.getPage(url);
		WebResponse response = page.getWebResponse();
		if (response.getContentType().equals("application/json")) {
			String json = response.getContentAsString();
			JSONArray jsonArray = JSONArray.fromObject(json);
			csairHtmlPage.setJsonArray(jsonArray);
			csairHtmlPage.setLS(CS.NONE);
			return csairHtmlPage;
		}
		return csairHtmlPage;
	}

}
